/**
 * 表格扩展按钮click事件
 */
 import {toast,getMultiLang } from 'nc-lightapp-front';
import { headSumHandle } from "./commonEvent";
import requestApi from '../requestApi';
import { setDefautValueAfterBodyAdd } from '../initTemplate';
import _ from "lodash-es"
import { updatacardTableData} from 'src/erm/sscrppublic/common/utils/changePageData';
import {setTableExtendCol} from '../initTemplate'



// 查看发票
function handleInvioceShow(props,currentRow){
    let multiLang = props.MutiInit.getIntl(2011);
    let bxToInvoice = window.presetVar.bxToInvoice
    // 获取当前点击行的key
    let pk_erminvoice = currentRow[0].values.pk_erminvoice.value
    // 获取接口返回的发票对应关系数组 {"交通key":['11','33344','566']}
    let invioces = bxToInvoice && bxToInvoice[pk_erminvoice]
    // 获取发票列表
    let invoice_Detail = props.cardTable.getVisibleRows('invoice_Detail')
    let goalInvioce = [] //符合的发票
    // 从发票页签中找到交通点击行对应的发票列
    invioces &&invioces.forEach((itemInvoice,index) => {
        let test = []
        test = invoice_Detail.filter((item) => {
            return item.values.pk_erminvoice.value === itemInvoice
        })
        goalInvioce = [...goalInvioce,...test]
    })

    if(invioces && goalInvioce.length){
        let wrap = document.getElementsByName('anchor-invoice_Detail')[0]
        // 获取发票页签表格行
        let trs = Array.from(wrap.querySelectorAll('div.table-style-wrapper div.table-next-body-inner-wrapper tr'))
        // 遍历发票页签所有行去除高亮样式
        trs.forEach((tr,index) => {
            tr.classList.remove('table-selected')
        })
        // 交通点击行相关连的发票
        let goalTrs = []
        goalInvioce.forEach((item,index) => {
            let oriTrs = []
            oriTrs = trs.filter((tr,index) => {
                return item.rowid === tr.attributes[1].value
            })
            goalTrs = [...goalTrs,...oriTrs]
        })
        goalTrs.forEach((item) => {
            item.classList.remove('table-selected')
            setTimeout(() => {
                item.classList.add('table-selected')
            })
        })
        
        goalTrs[0].scrollIntoView({block:'end'})
    } else{
        toast({color:'warning',content:multiLang && multiLang.get("201101BXFP-0001")});
    }
}
// 查看明细
function handleShowDetail(props,currentRow){
    //获取发票对应关系
    let invoiceToBx = window.presetVar.invoiceToBx
    let oriRow = ''
    // 获取发票key
    let pk_erminvoice = currentRow[0].values.pk_erminvoice.value
    console.log('pk_erminvoice',pk_erminvoice)
    let pk_bx = invoiceToBx[pk_erminvoice][0] //取出住宿等pk

    // 遍历上方所有页签找到与发票相关联行
    Object.values(presetVar.body).forEach((body,index) => {
        let currentTb = document.getElementsByName('anchor-'+ body)[0]
        // 获取当前行的页签所有行元素
        let trs = Array.from(currentTb.querySelectorAll('div.table-style-wrapper div.table-next-body-inner-wrapper tr'))
        trs.forEach((tr,index) => {
            tr.classList.remove('table-selected')
        })
        // 获取当前页签所有可见行
        let allRows = props.cardTable.getVisibleRows(body)
        // 排除发票页签自身
        if(body !== 'invoice_Detail' && body !== 'accrued_verify' && body !== 'er_bxcontrast'){
            // 遍历当前页签得到与发票点击行相关联的明细行
            oriRow = allRows.filter((item) => {
                return pk_bx === item.values.pk_erminvoice.value;
            });
            if (oriRow.length > 0) {
                // props.cardTable.focusRowByIndex(body,currentIndex)
                let currentTb = document.getElementsByName('anchor-' + body)[0];
                // 获取当前行的页签所有行元素
                let trs = Array.from(currentTb.querySelectorAll('div.table-style-wrapper div.table-next-body-inner-wrapper tr'));
                // 从当前页签中获取对应明细行
                let curTrs = trs.filter((item) => {
                    return oriRow.some((row) => row.rowid === item.attributes[1].value);
                });
                curTrs.forEach((item) => {
                    item.classList.remove('table-selected');
                    setTimeout(() => {
                        item.classList.add('table-selected');
                    }, 0);
                });
                // 滚动到对应位置
                curTrs[0].scrollIntoView({ block: 'end' });
            }
        }
    })

}

//关联发票
export function relateVoiceEvent(props,args,cancel,checkArr){
//    const colVal = props.cardTable.getColValue(moduleId, key,false, false)

    console.log('当前行=====',args)
    
    const {rowid,values} = args
    //查看当前的关联发票字段
    
   
    let invoicePkList = cancel?[]:checkArr
    let bodys = Object.values(window.presetVar.body);
    // let bodyarr = [];
    // let hideTable = this.state.hideTables;
    const _this = this
    // bodys.forEach((one) => {
    //     if (hideTable.indexOf(one) < 0) {
    //         bodyarr[bodyarr.length] = one;
    //     }
    // })
    let appcode = (props.getUrlParam("appcode") == undefined || props.getUrlParam("appcode") == '') ? props.getSearchParam("c") : props.getUrlParam("appcode");
    let pagecode = (props.getUrlParam("pagecode") == undefined || props.getUrlParam("pagecode") == '') ? props.getSearchParam("p") : props.getUrlParam("pagecode");
    let tablecode =  values.tablecode.value
    let billdata = props.createExtCardData(pagecode, "head", bodys);
    let pjdata = {
        "appcode" : appcode,
        "pagecode" : pagecode,
        "templateid" :  props.meta.getMeta().pageid,
        tablecode,
        "invoicePkList" : invoicePkList,
        "tradetype" : window.presetVar.tradetype,
        linkRowid:rowid
    }
   
    billdata.userjson = JSON.stringify(pjdata);
    billdata.templetid = props.meta.getMeta().pageid;
 
    
    requestApi.invoiceRelate({
        data: billdata,
        success: (data) => {
            
            props.form.setAllFormValue({ [window.presetVar.head.head1]: data.head[window.presetVar.head.head1] })
            
            const resBody = Object.keys(data.bodys)
            const nomalHideTable = _.clone(window.presetVar.hideTables)
            let hideTables = _this.state.hideTables
            nomalHideTable.forEach(item => {
                let index = hideTables.indexOf(item)
                if (resBody.indexOf(item) < 0) {
                    if (index < 0) {
                        hideTables.push(item)
                    }
                    _this.props.cardTable.setTableData(item, { rows: [] }, null, false)
                } else {
                    if (index > 0) {
                        hideTables.splice(index, 1)
                    }
                }
            })
            _this.setState({hideTables:hideTables})

            resBody.forEach((item) => {
                
                
              const newitemdata = data.bodys[item]
              if (newitemdata && newitemdata.rows) {
                const rows = []
                for (let i = 0; i < newitemdata.rows.length; i++) {
                  
                  if (newitemdata.rows[i].values) {
                    rows[rows.length] = newitemdata.rows[i]
                  }
                }
                newitemdata.rows = rows
              }
    
              newitemdata && props.cardTable.setTableData(item, newitemdata, null, false)
            })
            
            // if(cancel){
            //     props.cardTable.setTableData('invoice_Detail', {}, null, false)
            // }
            if(JSON.parse(data.userjson).invoiceToBx){
                window.presetVar.invoiceToBx = JSON.parse(data.userjson).invoiceToBx
                window.presetVar.bxToInvoice = JSON.parse(data.userjson).bxToInvoice
            }
            // 设置操作按钮的事件
              !cancel&&this.setState({showInvoiceRelate: false})
            //设置表格扩展列
            setTableExtendCol.call(this, props, props.meta.getMeta(), window.presetVar.buttonTpl.button);
           
        }
    })
}

function tableExtendButtonClick() {
    console.log('args===',this)
    
    let returnObj = {};
    let props = this?this.props:args[1]
    for(let name in window.presetVar.body){
        let areaId = window.presetVar.body[name];
        //点击关联发票
        returnObj['invoice_relate']= (...args) => {
            //模拟数据
            this.setState({
                showInvoiceRelate:true,
                currentRowInvoiceRelate:args[0]
            })
            let param = {};
            param.tradetype = window.presetVar.tradetype;
            param.pk_jkbx = props.form.getFormItemsValue("head","pk_jkbx").value;
            param.jkbxr = props.form.getFormItemsValue("head","jkbxr").value;
            param.pk_org = props.form.getFormItemsValue("head","pk_org").value;
            window.invoiceListQueryParam = param;
            // relateVoiceEvent.call(this,props,args[0])
        }
        //取消关联发票
        returnObj['invoice_cancel']= (...args) => {
            relateVoiceEvent.call(this,props,args[0],true)
        }

        returnObj[areaId +'_invoice_show']= (...args) => {
            
            handleInvioceShow(props,args)
        }
        returnObj[areaId +'_show_detail']= (...args) => {
            console.log(args)
            handleShowDetail(props,args)
        }
        if(areaId!=='accrued_verify' && areaId!=='er_bxcontrast'){
            let canDel = true
            returnObj[areaId +'_Delete']={
                beforeClick:(record, index) => {
                    console.log('before delete record:',record);
                    if((record.status == '1' || record.status == '0')&& record.values.pk_mtapp_detail&& record.values.pk_mtapp_detail.value) {
                        toast({content:'由申请生成的报销明细不允许删除,请知悉!', color:'danger'})
                        canDel = false
                        return false
                    }
                    return true
                },
                afterClick: (...args) => {
                   
                    canDel&&headSumHandle.call(this, args, 'delete', areaId);
                }
            };
            returnObj[areaId +'_Copy']={
                afterClick: (record, index) => {
                    
                    clearPropsAboutInvoices.call(this, props,areaId, index+1,'copy')
                    headSumHandle.call(this);
                    setTableCurentRowEditable.call(this,props,areaId,index)

                    
                }
            };

            returnObj[areaId + '_Attachment'] = {
                afterClick: (record, index) => {
                    showTableAttachment.call(this, record, index)
                }
            };
            returnObj[areaId + '_Edit'] = {
                afterClick: (record, index) => {
                    // 切换展开/收起按钮
                    if (record) {
                        if (record.expandRowStatus) { // 收起 2207 下方代码已经无效
                            let elem = document.querySelector(`.u-table-fixed-right tr[data-row-key='${record.rowid}'] a.row-btn-${areaId}_Edit`);
                            elem.innerHTML = '收起';
                        } else { // 展开
                            let elem = document.querySelector(`.u-table-fixed-right tr[data-row-key='${record.rowid}'] a.row-btn-${areaId}_Edit`);
                            elem.innerHTML = '展开';
                        }
                    }
                }
            };
            returnObj[areaId + '_Insert'] = {
                afterClick: (record, index) => {
                    clearPropsAboutInvoices.call(this, props,areaId, index+1)
                    setDefautValueAfterBodyAdd.call(this, props, areaId, index, true);
                }
            };
        }
    }
    
    return returnObj;
}
function setTableCurentRowEditable(props,moudleid,rowIndex){
    let paytarget = props.cardTable.getDataByIndex(moudleid, rowIndex).values['paytarget'].value
    
    let setIndex = rowIndex+1
    
    let editFreecust = props.form.getFormItemsDisabled(window.presetVar.head.head1,'freecust')
    props.cardTable.setEditableByIndex(moudleid,setIndex,'freecust',!editFreecust)

    
    
    // 增行时，本币汇率、汇率类型、汇率来源日期，需根据表头来设置表体其编辑性
    let bbhlFlag = props.form.getFormItemsDisabled('head', 'bbhl'); //表头本币汇率编辑性
    let zzhllxFlag = props.form.getFormItemsDisabled('head', 'zzhllx'); //表头本币汇率类型编辑性
    let zzhllyrqFlag = props.form.getFormItemsDisabled('head', 'zzhllyrq'); //表头本币汇率日期编辑性
    // 表头中本币种、汇率类型更改后，表体中本币汇率、汇率类型、汇率来源日期需同时控制其编辑性
    let editkeys = []
    let unedikeys = []
    bbhlFlag ? unedikeys.push('bbhl') : editkeys.push('bbhl')
    zzhllxFlag ? unedikeys.push('zzhllx') : editkeys.push('zzhllx')
    zzhllyrqFlag ? unedikeys.push('zzhllyrq') : editkeys.push('zzhllyrq')
    props.cardTable.setEditableByIndex(moudleid, setIndex, editkeys, true)
    props.cardTable.setEditableByIndex(moudleid, setIndex, unedikeys, false)

    //新增行时，清理掉与收款对象不匹配的其他字段的默认值
    if (paytarget == '0'){
        
        props.cardTable.setEditableByIndex(moudleid, [setIndex], ['hbbm','hbbm_v','customer','customer_v','custaccount','freecust'], false)
    }else if (paytarget == '1'){
     
        props.cardTable.setEditableByIndex(moudleid, [setIndex], ['receiver','customer','customer_v','skyhzh','custaccount'], false)
    }else if (paytarget == '2'){
        
        props.cardTable.setEditableByIndex(moudleid, [setIndex], ['receiver','hbbm','hbbm_v','skyhzh'], false)
    }
}
//清空发票相关的字段,处理行数据,模板没有的字段,使用setValByKeyAndIndex是无法清空的
export function clearPropsAboutInvoices(props,tableCode, index, from) {
    
    const filterKeys = ["pk_erminvoice", "pk_erminvoice_b", "fphm", "fpdm", "fplxpk"];
    const tableData = props.cardTable.getVisibleRows(tableCode)
    let fromIndex = from==='copy'?index-1:index
    if (tableData[fromIndex] && tableData[fromIndex].values) {
        
        let obj = { ...tableData[fromIndex].values }
        filterKeys.forEach(key => {
            obj[key] = { display: null, value: null }
        })
        tableData[index].values = obj
    }
    props.cardTable.setTableDataWithResetInitValue(tableCode, { rows: tableData })
}

function showTableAttachment(record, index) {
    console.log('record:', record, index)
    const props = this.props;
    let billId = props.getUrlParam('billid') || this.state.billId || "";
    let billtype = window.presetVar.tradetype || "";

    const params = {}
    if(record.values.pk_busitem) pathis.setStaterams.pk_busitem = record.values.pk_busitem.value
    if(record.values.pk_erminvoice) params.pk_erminvoice = record.values.pk_erminvoice.value
    if(record.values.generatetype) params.generatetype = record.values.generatetype.value

    if (billId == "" && !this.state.showTableUploader){
        //去后台生成单据主键
        requestApi.generatBillId({
            data: {billtype: billtype},
            success:(data)=>{
                let accessorypkfildname = data["pkfieldName"];
                billId = data[accessorypkfildname];
                setTimeout(() => {
                    this.setState({
                        billId: billId ,
                        showTableUploader: !this.state.showTableUploader,
                        reqTableAttachParam: params
                    });
                })

                this.accessorybillid = billId;
            },
            error:(data)=>{
                toast({ content: data.message, color: 'danger' });
            }
        });
    } else {
        setTimeout(() => {
            this.setState({
                billId: billId ,
                showTableUploader: !this.state.showTableUploader,
                reqTableAttachParam: params
            });
        })
    }
}

export default tableExtendButtonClick;
